<?php

namespace App\Admin\Traits;

use App\Models\Category;
use App\Models\Product;

trait ModelTree
{
    public function delete()
    {
        $deleteId = $this->getKey();
        $pid = $this->parentColumn;
        $category = Category::select('id', $pid)->find($deleteId);

        if (count($category->children) >= 1)
            return false;

        if ($category->$pid == 0)
        {
            $product = Product::where('category_id', $deleteId)
                ->select('id', 'category_id')
                ->first();
            if ($product)
                return false;
        }

        Product::where('category_id', $deleteId)->update(['category_id' => $category->$pid]);

        $this->where($this->parentColumn, $this->getKey())->delete();
        return parent::delete();
    }
}